%Up or downsamples a 2D image I
%Arguments: image I, type 'up' or 'down', and odd (include only when 
%upsampling) is the 2-element vector indicating whether rows and cols of
%image are odd or even (in size)

function S = resample2D(I,type,odd)
filter = [1, 4, 6, 4, 1]./16;%Normalized 5th row of Pascal Triangle, 
%represents 5 tap Gaussian filter

if strcmp(type,'down') 
    %applying the gaussian low pass filter (twice because to rows and cols)
    I = imfilter(I,filter,'symmetric');
    I = imfilter(I,transpose(filter),'symmetric');
    r = size(I,1);
    c = size(I,2);
    %downsample by skipping every second sample in rows and columns for
    %each channel:
    S = I(1:2:r, 1:2:c, :);
    
elseif strcmp(type,'up')
    I = padarray(I,[1 1 0],'replicate'); %padding the borders with zeros to
    %serve as placeholders for future new upsampled samples
    r = 2*size(I,1);
    c = 2*size(I,2);
    k = size(I,3);
    S = zeros(r,c,k); %preallocate for the upsampled image
    S(1:2:r, 1:2:c, :) = 4*I; %multiply by 2 twice (rows and cols) to
    %account for the attenuation of the filter
    
    %filter (interpolate zeros) rows and columns
    S = imfilter(S,filter);
    S = imfilter(S,transpose(filter));

    %get rid of zeros at the borders, use "odd" to get the right size
    S = S(3:r - 2 - odd(1), 3:c - 2 - odd(2), :);
else
    error('Resampling type (up or down) cannot be parced');
end
end



